package com.joe.lucene;

import java.io.IOException;
import java.util.Date;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.joe.lucene.analyzer.MarcAnalyzer;
import com.joe.utils.io.GetString;

public class LuceneTest {
	
	private static String index_dir = "F:\\opacindex\\solr\\data\\index";
	private static Directory fsDir = null;
	private static IndexSearcher indexSearcher = null;
	static{
		try {
			fsDir = FSDirectory.getDirectory(index_dir);
			indexSearcher = new IndexSearcher(fsDir);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void search(String q) throws ParseException, IOException{
		Query query = new QueryParser("marc",new MarcAnalyzer()).parse(q);
		long start = new Date().getTime();
		Hits hits = indexSearcher.search(query);
		long end = new Date().getTime();
		for(int i=0;i<hits.length();i++){
			if(i>20){
				break;
			}
			Document doc = hits.doc(i);
			System.out.println(i+"->title:"+doc.get("title")+",author:"+doc.get("author")+",curlocal:"+doc.get("curlocal"));
		}
		//+title:java +hasholding:y +(curlocal:w curlocal:z)
		//(title:7) AND (libcode:PFQ OR libcode:XFQ OR libcode:ACH) <==> +title:7 +(libcode:pfq libcode:xfq libcode:ach)
		System.out.println(q+"<==>"+query);
		System.err.println("Found "+hits.length()+" document(s) (in "+(end-start)+
				" milliseconds) that matched query '"+q+"'");
	}
	
	public static void run() throws ParseException, IOException{
		String str = null;
		while(!(str=GetString.getString()).equals("end")){
			search(str);
		}
	}
	
	/**
	 * @param args
	 * @throws IOException 
	 * @throws ParseException 
	 */
	public static void main(String[] args) throws ParseException, IOException {
		run();
	}

}
